package org.example.JUC;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class CountDownLatchTest {

    private static final CountDownLatch countDownLatch = new CountDownLatch(5);

    private static final ExecutorService executor = Executors.newFixedThreadPool(5);

    public static void main(String[] args) throws InterruptedException {

        System.out.println(Thread.currentThread().getName() + " 饭点");
        for (int i = 0; i < 5; i++) {
            executor.submit(new Worker());
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + " 一起去吃饭!");
        executor.shutdown();
    }

    static class Worker extends Thread {
        @Override
        public void run() {
            try {
                TimeUnit.MILLISECONDS.sleep(1000 + new Random().nextInt(2000));
                System.out.println(Thread.currentThread().getName() + " 开始下楼");
                TimeUnit.MILLISECONDS.sleep(1000 + new Random().nextInt(5000));
                System.out.println(Thread.currentThread().getName() + " 到了楼下");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
        }
    }
}
